/*   Valhalla MailChecker -- Simple IMAP Mail Checker
*    Copyright (C) 2010-2011  Guillaume Florimond (gflorimond at gmail dot com)
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package fr.valhalla.mailcheck;

import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;
import fr.valhalla.mailcheck.gui.classic.AccountList;
import fr.valhalla.mailcheck.gui.SysTray;
import fr.valhalla.mailcheck.utils.EncryptedProperties;
import java.awt.SystemTray;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.UIManager;

/**
 *
 * @author guillaume
 */
public class Kernel {

    private boolean gui = true;

    // Classes
    private SysTray systray;
    private GlobalPreferences globalPreferences;

    // Tools
    private String masterpassword;
    private Vector checkers;

    // GUI
    private AccountList accountList;


    public Kernel() {
        // Initialisation des préférences (masterpassword)
        globalPreferences = new GlobalPreferences();

        checkers = new Vector();
    }

    public void startWithGUI() {
        System.out.println("Starting MailCheck GUI...");
        
        // Set Nimbus L&F
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        } catch(Exception e) {;}

        //Check the SystemTray is supported
        if (!SystemTray.isSupported()) {
            if(globalPreferences.showGUIWarnings)
                showGUIWarning("Systemtray is not supported on your desktop.");
            else
                System.out.println("SystemTray is not supported on your desktop.");
        }
        else
            systray = new SysTray(this);

        // Ask for master password
        masterpassword = getPassword();

        // Main frame
        accountList = new AccountList(this);

        // Affichage de la fenêtre principale ...
        if (    globalPreferences.openMainWindowOnStart // ... si les préférences indiquent de l'afficher
            ||  !SystemTray.isSupported()               // ... si le systray est indisponible (si on n'affiche pas la fenêtre, on ne peut plus rien faire)
           ) {
            accountList.setVisible(true);
        }

        // Start checkers
        startCheckers();
    }

    public void startWithoutGUI() {
        System.out.println("Starting MailCheck in console mode (without GUI)...");

        gui = false;
        masterpassword = ConsoleMode.readFromConsole("Entrez le mot de passe global: ");

        // Start checkers
        startCheckers();
    }

    // GETTERS

    public GlobalPreferences getGlobalPreferences() {
        return globalPreferences;
    }

    public SysTray getSystray() {
        return systray;
    }

    public AccountList getAccountList() {
        return accountList;
    }

    public boolean withGUI() {
        return gui;
    }

    // TOOLS

    private String getPassword() {
        // Données
        String pwd = null;
        Object[] message = new Object[2];
        message[0] = "Saisissez le mot de passe global:"; //Message apparaîssant dans le corps du dialog
        message[1] = new JPasswordField();

        String option[] = {"Nouveau compte...", "Valider"};

        int result = JOptionPane.showOptionDialog(
                null, // fenêtre parente
                message, // corps du dialogue
                "Mot de passe global",// Titre du dialogue
                JOptionPane.DEFAULT_OPTION, // type de dialogue
                JOptionPane.QUESTION_MESSAGE, // type icone
                null, // icône optionnelle
                option, // boutons
                message[1] // objet ayant le focus par défaut
                );

        if (result == 1) {
            pwd = new String(((JPasswordField) message[1]).getPassword());
        }

        return pwd;
    }

    private void showGUIWarning(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

    private void startCheckers() {
        // Password entered
        if ((masterpassword != null) && (masterpassword.length() > 0)) {
            try {
                EncryptedProperties props = new EncryptedProperties(masterpassword);
                try {
                    FileInputStream in = new FileInputStream("fr.valhalla.mailcheck.accounts.properties");
                    props.load(in);
                    in.close();
                } catch (FileNotFoundException e) {
                    // Le fichier n'existe pas : on le crée
                    try {
                        props.store(new FileOutputStream(new File("fr.valhalla.mailcheck.accounts.properties")), null);
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Iterator i = props.keySet().iterator();
                while (i.hasNext()) {
                    String key = (String) i.next();
                    if (key.substring(0, 4) == null ? "acco" == null : key.substring(0, 4).equals("acco")) {
                        String accountName = props.getProperty(key);
                        // LANCEMENT DU CHECKER ICI
                        Checker c = new Checker(new Account(accountName, masterpassword), this);
                        if(gui) accountList.getContentPane().add(c.getCheckPanel());
                        c.start();
                        checkers.add(c);
                        // --
                        System.out.println("Checher started: " + c.getName());
                    }
                }
            } catch(Exception e) {e.printStackTrace();}
            finally {
                if(gui) accountList.pack();
            }
        }
        else return;
    }


    public Vector getCheckers() {
        return checkers;
    }

    public Checker getChecker(int index) {
        return (Checker)checkers.elementAt(index);
    }
}
